import { isNumber } from 'microconnect-common/utils/is';
import { divide, toFixed2 } from 'microconnect-common/utils/math';
import { getCSSColor, getCSSVariable } from './color';

export const loadingOption = {
  text: '',
  color: '#409eff',
  textColor: '#000',
  maskColor: 'rgba(255, 255, 255, 0.05)',
  // 字体大小。从 `v4.8.0` 开始支持。
  fontSize: 12,
  // 是否显示旋转动画（spinner）。从 `v4.8.0` 开始支持。
  showSpinner: true,
  // 旋转动画（spinner）的半径。从 `v4.8.0` 开始支持。
  spinnerRadius: 17,
  // 旋转动画（spinner）的线宽。从 `v4.8.0` 开始支持。
  lineWidth: 2,
  // 字体粗细。从 `v5.0.1` 开始支持。
  fontWeight: 'normal',
  // 字体风格。从 `v5.0.1` 开始支持。
  fontStyle: 'normal',
  // 字体系列。从 `v5.0.1` 开始支持。
  fontFamily: 'sans-serif'
};
// 文字长度过大时就会换行
export const getBreakText = (text: string, maxLength = 14): string => {
  if (text.length > maxLength) {
    const t1 = text.substr(0, maxLength);
    const t2 = getBreakText(text.substr(maxLength - text.length));
    return `${t1}<br/>${t2}`;
  }
  return text;
};
export const axisLabel: echarts.EChartOption.BasicComponents.CartesianAxis.Label = {
  fontSize: 12,
  color: getCSSColor('grey-9')
};

/** 线条颜色 */
export const gridColor = getCSSColor('grey-2');

/** 单位变量配置 */
export const unitVarConfig = {
  number: '（个）',
  yuan: '（元）',
  tenThousand: {
    label: '（万）',
    get: (num: number | string) => {
      return toFixed2(divide(num, 10000));
    }
  }
};

export const axisLine = {
  lineStyle: {
    color: 'rgba(0 ,0 ,0 , 0.08)'
  }
};

export const legendConfig: echarts.EChartOption.Legend = {
  top: '0',
  right: '0',
  textStyle: {
    color: getCSSColor('grey-8')
  }
};

// 获取默认的图例配置
export const getLegendConfig = (
  list: string[],
  icon: string = 'square',
  legendConfig: echarts.EChartOption.Legend = { itemWidth: 8, itemHeight: 8 }
) => {
  return {
    data: list.map((name) => ({ name, icon })),
    ...legendConfig
  };
};

export const tooltipConfig: echarts.EChartOption.Tooltip = {
  backgroundColor: 'rgba(255, 255, 255, 0.04)',
  borderWidth: 0,
  ...{ className: 'echarts-tooltip' },
  textStyle: {
    color: getCSSColor('grey-5')
  },
  transitionDuration: 0,
  axisPointer: {
    type: 'cross',
    shadowStyle: {
      color: 'box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.12);'
    },
    label: {
      show: false,
      color: getCSSColor('black')
    }
  }
};

export const gridConfig: echarts.EChartOption.Grid = {
  left: '0',
  right: '0',
  bottom: '0',
  containLabel: true,
  show: true,
  borderWidth: 1,
  borderColor: getCSSColor('grey-2')
};

export const splitLineX: echarts.EChartOption.BasicComponents.CartesianAxis.SplitLine = {
  show: true,
  lineStyle: {
    type: 'dashed',
    color: getCSSColor('grey-1')
  }
};

export const splitLineY = splitLineX;

export const titleTextStyleConfig: echarts.EChartOption.TextStyle = {
  color: getCSSColor('grey-5'),
  fontSize: 22,
  fontWeight: 500
};

export const xAxisConfig: echarts.EChartOption.XAxis = {
  data: [],
  axisLine: {
    ...axisLine
  },
  axisLabel: {
    ...axisLabel,
    show: true,
    fontSize: 13,
    formatter: '{value}'
  },
  splitLine: splitLineX,
  axisTick: {
    show: false
  }
};

export const yAxisConfig: echarts.EChartOption.YAxis = {
  type: 'value',
  nameTextStyle: {
    align: 'right',
    color: getCSSColor('grey-5')
  },
  axisLabel: {
    show: true,
    ...axisLabel
  },
  splitLine: {
    lineStyle: {
      type: 'dashed',
      color: splitLineY.lineStyle?.color
    }
  }
};
export interface ITooltipItem {
  label: string;
  color?: string;
  value: string[];
}
/**
 * @desc tooltip格式调整
 */
export const tooltipFormatter = (title: string, items: ITooltipItem[], extendHtml?: string) => {
  const htmlList = items
    .map((item) => {
      if (!item) return '';
      const { color, label, value } = item;
      return `<div style="margin: 0px 0 0;line-height:1.6;">
            ${
              color
                ? `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`
                : ''
            }
            <span style="font-size:14px;color:var(--color-grey-50);font-weight:400;margin-left:2px">${label}</span>
            <span style="float:right;margin-left:20px;font-size:14px;color:var(--color-grey-50);font-weight:900">${value?.join(
              ''
            )}</span>
            <div style="clear:both">
            ${extendHtml ? extendHtml : ''}
          </div>`;
    })
    ?.join('');
  let str = htmlList
    ? `
    <div style="color:var(--color-grey-50); font-size: 14px;padding-bottom: 5px;">${title}</div>
    <div style="line-height:1;">
      ${htmlList}
      <div style="clear:both"></div>
    </div>`
    : '';
  return str;
};
/** Y轴分割数及最大值控制 */
export const yInterval: echarts.EChartOption.YAxis = {
  minInterval: 1,
  max(val) {
    return Math.floor(val.max * 1.5);
  }
};

export const seriesBarStyle: echarts.EChartOption.SeriesBar = {
  barWidth: 16,
  itemStyle: {
    borderRadius: 0,
    color: getCSSVariable('chart-1')
  }
};
// 主题颜色，由浅到深
export const getThemeColors = () => {
  return [
    getCSSColor('green-1'),
    getCSSColor('green-2'),
    getCSSColor('green-3'),
    getCSSColor('green-4'),
    getCSSColor('green-5'),
    getCSSColor('green-6'),
    getCSSColor('green-7'),
    getCSSColor('green-8'),
    getCSSColor('green-9')
  ];
};
/** 根据数据量计算可是区域条数 */
export const getViewMax = (showLength: number, dataLength: number) => {
  return (Math.max(Math.min(dataLength, showLength), showLength) / dataLength) * 100;
};

export const toChartData = (...arr: any[]) => {
  const newArr = arr.filter(Boolean);
  const viewCount = newArr.filter(Boolean).map((item) => item?.view?.length || 0);
  const maxViewCount = Math.max(...viewCount);
  const maxIndex = viewCount.indexOf(maxViewCount);
  const dateList = newArr[maxIndex]?.view;

  const dataList = newArr.map((item, index) => {
    if (maxIndex === index || item.view?.length === maxViewCount) {
      return newArr[index].value?.map((item: any) => Number(toFixed2(item)));
    }
    return dateList?.map((date: any) => {
      if (!item || !item.view) {
        return null;
      }
      const dateIndex = item.view.indexOf(date);
      if (dateIndex > -1) {
        const value = item.value[dateIndex];
        return isNumber(value) ? Number(toFixed2(value)) : null;
      }
      return null;
    });
  });
  return { dateList, dataList };
};
